local math = math 
local math_floor = math.floor 
local math_type  = math.type
local math_max  = math.max
local math_min  = math.min
local math_lerp = math.lerp 

local color = {}

function color.random()
    local r = math.random(0, 255)
    local g = math.random(0, 255)
    local b = math.random(0, 255)
    local a = 255
    return ((a << 24) + (r << 16) + (g << 8) + b)
end

function color.hex(r, g, b, a)
    r = math_max(math_min(math_floor(r or 255), 255), 0) 
    g = math_max(math_min(math_floor(g or 255), 255), 0) 
    b = math_max(math_min(math_floor(b or 255), 255), 0) 
    a = math_max(math_min(math_floor(a or 255), 255), 0) 
    return ((a << 24) + (r << 16) + (g << 8) + b)
end

function color.rgba(hex)
    local r, g, b, a = 255, 255, 255, 255
    if math_type(hex) == 'integer' and hex > 0 and hex <= 0xffffffff then 
        r = (hex << 40) >> 56
        g = (hex << 48) >> 56
        b = (hex << 56) >> 56
        a = (hex << 32) >> 56
    end
    return r, g, b, a
end

function color.lerp( a, b, t )
    local r1, g1, b1, a1 = color.rgba(a)
    local r2, g2, b2, a2 = color.rgba(b)
    return color.hex(
        math_lerp( r1, r2, t),
        math_lerp( g1, g2, t),
        math_lerp( b1, b2, t),
        math_lerp( a1, a2, t)
    )
end

function color.bezier( a, b, c, t )
    local r1, g1, b1, a1 = color.rgba(a)
    local r2, g2, b2, a2 = color.rgba(b)
    local r3, g3, b3, a3 = color.rgba(c)
    return color.hex(
        math_lerp(math_lerp(r1, r3, t), math_lerp(r3, r2, t), t), 
        math_lerp(math_lerp(g1, g3, t), math_lerp(g3, g2, t), t), 
        math_lerp(math_lerp(b1, b3, t), math_lerp(b3, b2, t), t), 
        math_lerp(math_lerp(a1, a3, t), math_lerp(a3, a2, t), t)
    )
end

return color